package ecommerce.user.behavior.analysis.test;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class MultiThreadRequestSender {

    public static void main(String[] args) {
        // 接口的URL
        String url = "http://localhost:8090/userBehavior/PathConversionRate"; // 替换为实际接口地址
        String token = "your_jwt_token"; // 替换为实际的JWT令牌

        // 请求总数
        int totalRequests = 100; // 总请求数
        int requestsPerSecond = 100; // 每秒发送的请求数

        // 创建线程池，线程池大小等于每秒请求数
        ExecutorService executor = Executors.newFixedThreadPool(requestsPerSecond);

        // 使用OkHttpClient
        OkHttpClient client = new OkHttpClient();

        // 使用CountDownLatch等待所有任务完成
        CountDownLatch latch = new CountDownLatch(totalRequests);

        // 发送请求的逻辑
        Runnable sendRequests = () -> {
            IntStream.range(0, totalRequests).forEach(i -> {
                // 提交请求任务
                executor.submit(() -> {
                    try {
                        // 构建请求
                        Request request = new Request.Builder()
                                .url(url)
                                .addHeader("Authorization", token)
                                .get()
                                .build();

                        // 发送请求并处理响应
                        System.out.println("Sending request " + (i + 1));
                        Response response = client.newCall(request).execute();

                        if (response.isSuccessful()) {
                            // 打印返回值
                            System.out.println("Response for request " + (i + 1) + ": " + response.body().string());
                        } else {
                            System.err.println("Request " + (i + 1) + " failed with status code: " + response.code());
                        }

                        response.close();
                    } catch (IOException e) {
                        System.err.println("Error during request " + (i + 1) + ": " + e.getMessage());
                    } finally {
                        // 完成任务
                        latch.countDown();
                    }
                });

                // 控制每秒请求数
                try {
                    Thread.sleep(1000 / requestsPerSecond); // 每秒 40 次请求，间隔 25 毫秒
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.err.println("Thread interrupted: " + e.getMessage());
                }
            });
        };

        // 启动请求任务
        new Thread(sendRequests).start();

        // 等待所有任务完成
        try {
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("Execution interrupted: " + e.getMessage());
        }

        // 关闭线程池
        executor.shutdown();
        System.out.println("All requests completed.");
    }
}